<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class AdminController extends CI_Controller {
	function __construct(){
		parent::__construct();
		$this->load->helper('auth');
		$this->load->library('session');
		if(!$this->isLogin() ) {
			redirect('/passport/login');
			return;
		}
	}

	function isLogin() {
		return true;
		$this->load->library('session');
		$user = $this->session->userdata('user');
		if(!$user) {
			$agentId = $this->input->get_post('agentId');
			$session = $this->input->get_post('session');
			if( ! empty($session)){
				$session = json_decode(urldecode($session), TRUE);
				$this->session->userdata = $session;
				$user = $this->session->userdata('user');
			}elseif( ! empty($agentId)){
				$this->load->model('desktop/admin_user_model');
				$user = $this->admin_user_model->findUserByName($agentId);
				if(empty($user)){
					return false;
				}
				$data = array();
				$data['userId'] = $user['userId'];
				$data['username'] = $user['username'];
				$data['mobile'] = $user['mobile'];
				$data['super'] = $user['super'];
				$data['isLogin'] = true;
				$this->session->set_userdata('user', $data);
			}else{
				return false;
			}
		}
		if( ! (isset($user['isLogin']) && $user['isLogin'])){
			return false;
		}
		return true;
	}

	/*
	 * 权限验证
	 */
	function checkAuth($auth , $exit=true){
		$user = $this->session->userdata('user');
		$this->load->model('desktop/admin_user_model' , 'usermdl');
		//超级管理员
		if(isset($user['super']) && $user['super'] == 'true'){
			return true;
		}
		//权限是否已经定义
		$this->load->model('desktop/admin_operation_model' , 'opmdl');
		$op = $this->opmdl->findOperationByOp($auth);
		if(empty($op)){
			//验证结束后清除db，以便后面的模块load自己的数据库
			$this->db = '';
			return true;
		}
		//验证用户权限
		$ret = $this->usermdl->checkAuth($auth , $user);
		if( ! $ret && $exit){
			$data['error'] = $msg ? $msg : '您没有权限使用此功能';
			$data['redirect'] = null;
			$this->output->set_header('Content-Type: text/jcmd; charset=utf-8');
			echo json_encode($data);
			exit(0);
		}
		$this->db = '';
		return $ret;
	}
}
?>
